<template>
  <div class="quality-table-container">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="showAddDialog" icon="el-icon-plus">新增记录</el-button>
    </div>

    <!-- 查询表单 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="产线">
          <el-select v-model="filterForm.lineId" placeholder="请选择产线" clearable @change="tableShowIf">
            <el-option v-for="line in lineOptions" :key="line.line_id" :label="line.line_name"
              :value="line.line_id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="日期范围">
          <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>

        <el-form-item label="MPN">
          <el-input v-model="filterForm.mpn" placeholder="请输入MPN" clearable></el-input>
        </el-form-item>

        <el-form-item label="Lot">
          <el-input v-model="filterForm.lot" placeholder="请输入Lot号" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="warning" @click="handleExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%;height: 600px;" max-height="600" v-loading="loading"
      v-if="tableShow" @sort-change="handleSortChange">
      <el-table-column prop="qcId" label="ID" width="80" sortable></el-table-column>
      <el-table-column prop="date" label="日期" width="120" sortable>
        <template slot-scope="scope">
          {{ formatDate(scope.row.date) }}
        </template>
      </el-table-column>
      <el-table-column prop="date" label="时间" width="100">
        <template slot-scope="scope">
          {{ formatTime(scope.row.date) }}
        </template>
      </el-table-column>
      <el-table-column prop="shift" label="班次" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.shift === 'A' ? 'primary' : 'success'">
            {{ scope.row.shift }}班
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mpn" label="MPN" width="150"></el-table-column>
      <el-table-column prop="lot" label="Lot" width="150"></el-table-column>
      <el-table-column prop="machineNumber" label="机台号" width="100"></el-table-column>
      <!-- 质检确认 -->
      <el-table-column label="模具品质确认" width="180">
        <el-table-column prop="qcfF" label="初" width="80">
          <template slot-scope="scope">
            <status-tag :status="scope.row.qcfF"></status-tag>
          </template>
        </el-table-column>
        <el-table-column prop="qcfM" label="中" width="80">
          <template slot-scope="scope">
            <status-tag :status="scope.row.qcfM"></status-tag>
          </template>
        </el-table-column>
        <el-table-column prop="qcfE" label="终" width="80">
          <template slot-scope="scope">
            <status-tag :status="scope.row.qcfE"></status-tag>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column label="EC治具品质确认" width="180">
        <el-table-column prop="qceF" label="初" width="80">
          <template slot-scope="scope">
            <status-tag :status="scope.row.qceF"></status-tag>
          </template>
        </el-table-column>
        <el-table-column prop="qceM" label="中" width="80">
          <template slot-scope="scope">
            <status-tag :status="scope.row.qceM"></status-tag>
          </template>
        </el-table-column>
        <el-table-column prop="qceE" label="终" width="80">
          <template slot-scope="scope">
            <status-tag :status="scope.row.qceE"></status-tag>
          </template>
        </el-table-column>
      </el-table-column>


      <el-table-column prop="processId" label="工艺id" width="100" v-if="false" />
      <el-table-column prop="qcId" label="质检id" width="100" v-if="false" />
      <el-table-column prop="admit" label="提交人" width="100"></el-table-column>
      <el-table-column prop="moldCheck" label="模具检查" width="100">
        <template #header>

          <el-tooltip class="item" effect="dark" placement="top">
            <i class="el-icon-question smartTip"><B>模具检查</B></i>
            <div style="width: 220px;" slot="content">{{ prompt }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="remark" label="备注" width="120"></el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="210" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row, 1)">复制</el-button>
          <el-button size="mini" @click="handleEdit(scope.row, 2)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            v-hasPermi="['qcsystem:moldqcdata:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="pagination.pageNum" :page-sizes="[10, 20, 50]" :page-size="pagination.pageSize" v-if="tableShow"
      layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" @close="resetForm">
      <el-form :model="formData" :rules="formRules" ref="qualityForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产线" prop="lineId">
              <el-select v-model="formData.lineId" placeholder="请选择产线">
                <el-option v-for="line in lineOptions" :key="line.line_id" :label="line.line_name"
                  :value="line.line_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次" prop="shift">
              <el-select v-model="formData.shift" placeholder="请选择班次">
                <el-option label="A班" value="A"></el-option>
                <el-option label="B班" value="B"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="MPN" prop="mpn">
              <el-input v-model="formData.mpn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Lot" prop="lot">
              <el-input v-model="formData.lot" @input="checkPhoneLength"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机台" prop="machineNumber">
              <el-input v-model="formData.machineNumber" @input="checkPhoneLength"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模具检查" prop="moldCheck">
              <el-input v-model="formData.moldCheck"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="qcId" prop="qcId" v-if="false">
              <el-input v-model="formData.qcId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="模具品质确认" prop="qcfStatus">
          <b style="margin-left: 20px;margin-right: 10px;">初</b>
          <el-select v-model="formData.qcfF" placeholder="请选择" clearable @change="tableShowIf">
            <el-option v-for="moldqc in moldqcdata" :key="moldqc" :label="moldqc" :value="moldqc"></el-option>
          </el-select>
          <b style="margin-left: 20px;margin-right: 10px;">中</b>
          <el-select v-model="formData.qcfM" placeholder="请选择" clearable @change="tableShowIf">
            <el-option v-for="moldqc in moldqcdata" :key="moldqc" :label="moldqc" :value="moldqc"></el-option>
          </el-select>
          <b style="margin-left: 20px;margin-right: 10px;">终</b>
          <el-select v-model="formData.qcfE" placeholder="请选择" clearable @change="tableShowIf">
            <el-option v-for="moldqc in moldqcdata" :key="moldqc" :label="moldqc" :value="moldqc"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="EC治具品质确认" prop="qceStatus">
          <b style="margin-left: 20px;margin-right: 10px;">初</b>
          <el-select v-model="formData.qceF" placeholder="请选择" clearable @change="tableShowIf">
            <el-option v-for="moldqc in ecmoldqcdata" :key="moldqc" :label="moldqc" :value="moldqc"></el-option>
          </el-select>
          <b style="margin-left: 20px;margin-right: 10px;">中</b>
          <el-select v-model="formData.qceM" placeholder="请选择" clearable @change="tableShowIf">
            <el-option v-for="moldqc in ecmoldqcdata" :key="moldqc" :label="moldqc" :value="moldqc"></el-option>
          </el-select>
          <b style="margin-left: 20px;margin-right: 10px;">终</b>
          <el-select v-model="formData.qceE" placeholder="请选择" clearable @change="tableShowIf">
            <el-option v-for="moldqc in ecmoldqcdata" :key="moldqc" :label="moldqc" :value="moldqc"></el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="formData.remark"></el-input>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { lineList, getMpn14ByLot } from "@/api/qcsystem/qcdata"
import { qualityConfirmationList, addQualityConfirmation, updateQualityConfirmation, deleteQualityConfirmation, handleExport, getNewMoldDataIfNull } from "@/api/qcsystem/qcmolddata"

// 状态标签组件
const StatusTag = {
  props: ['status'],
  render(h) {
    return h('el-tag', {
      class: {
        'status-tag': true,
        'status-ok': this.status === 'OK',
        'status-ng': this.status !== 'OK'
      }
    }, this.status)
  }
}
components: {
  StatusTag
}

export default {
  components: {
    StatusTag
  },
  name: 'QualityTable',
  data() {
    return {
      moldqcdata: ['√', '毛边', '打痕', '冲压偏移', '段差', '脏污','暂无'],
      ecmoldqcdata: ['√', '探针打痕', '异物打痕', '伤痕', '制品打痕', '部品打痕','暂无'],
      tableShow: 0,
      filterForm: {
        lineId: '',
        dateRange: [],
        mpn: '',
        lot: ''
      },
      lineOptions: [],
      parameters: [
        { key: '贴合时间', label: '贴合时间', unit: 'ms' },
        { key: '吸嘴下压量', label: '吸嘴下压量', unit: 'mm' }
      ],
      loading: false,
      tableData: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      prompt: `上、下模：无异物、伤痕、凹凸、锈迹；
              导向柱、套：无破损、松动、脱落；
              刀片：无变形、缺口；
              海绵垫：无破损、脱落；
              制品定位销：无缺少、断裂；
              动作：配合良好、无异常声音；`,
      qualityConfirmData: [],
      // 新增功能相关数据
      dialogVisible: false,
      dialogTitle: '新增质量记录',
      currentId: null,
      formData: {
        qcId: '',
        lineId: '',
        shift: '',
        mpn: '',
        lot: '',
        qcStatus: 'OK',
        moldCheck: '',
        remark: '',
      },
      formRules: {
        lineId: [{ required: true, message: '请选择产线', trigger: 'change' }],
        shift: [{ required: true, message: '请选择班次', trigger: 'change' }],
        mpn: [{ required: true, message: '请输入MPN', trigger: 'blur' }],
        machineNumber: [{ required: true, message: '请输入机台', trigger: 'blur' }],
        lot: [
          { required: true, message: '请输入Lot号', trigger: 'blur' },
          {
            pattern: /^\d{11}$/,
            message: 'Lot号必须为11位数字',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getLine()
  },
  methods: {
    checkPhoneLength() {
      if (this.formData.lot.length == 11) {
        this.getMpnByLot(this.formData.lot);
      }
    },
    getMpnByLot(lot) {
      getMpn14ByLot(lot).then(response => {
        this.formData.mpn = response.data[0].mpn
      })
    },

    //导出
    //excel使用
    handleExcel() {
      this.$confirm("确认导出用户数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 调用导出接口
        handleExport().then(response => {
          const url = URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', '品质数据.xlsx');
          document.body.appendChild(link);
          link.click();
        });
      });
    },

    // 辅助方法：
    tableShowIf() {
      this.tableShow = 1;
    },
    fetchData() {
      const tableDatalist = []
      qualityConfirmationList(this.filterForm.lineId, this.pagination.pageNum, this.pagination.pageSize, this.filterForm.dateRange[0], this.filterForm.dateRange[1], this.filterForm.mpn, this.filterForm.lot).then(response => {

        this.loading = true
        this.pagination.total = response.total
        for (let index = 0; index < response.list.length; index++) {
          const element = response.list[index];
          tableDatalist.push(element);
        }
        this.loading = false
      })

      this.tableData = tableDatalist;
    },
    getLine() {
      lineList().then(response => {
        this.lineOptions = response
      })
    },

    // 新增功能方法
    showAddDialog() {
      this.dialogTitle = '新增质量记录'
      if (this.filterForm.lineId) {
        getNewMoldDataIfNull(this.filterForm.lineId).then(response => {
          if (response) {
            this.currentId = null
            this.dialogVisible = true
            this.formData.lineId = this.filterForm.lineId
          } else {
            this.$message.error("上一条数据未处理完成，请先处理上一条数据")
          }
        })
      } else {
        this.$message.error('请先选择产线')
      }
    },

    handleEdit(row, index) {
      this.currentId = index
      if (index == 1) {
        this.dialogTitle = '复制质量记录'
      } else {
        this.dialogTitle = '编辑质量记录'
      }
      // 转换数据格式适配表单
      this.formData = {
        qcId: row.qcId,
        lineId: row.lineId,
        shift: row.shift,
        mpn: row.mpn,
        lot: row.lot,
        machineNumber: row.machineNumber,
        qcStatus: row.qcStatus,
        remark: row.remark,
        qcfF: row.qcfF,
        qcfM: row.qcfM,
        qcfE: row.qcfE,
        qceE: row.qceE,
        qceM: row.qceM,
        qceF: row.qceF,
        moldCheck: row.moldCheck,
      }

      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQualityConfirmation(row.qcId).then(() => {
          this.$message.success('删除成功!')
          this.fetchData()
        }).catch(error => {
          this.$message.error(`删除失败: ${error.message}`)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },



    submitForm() {
      this.$refs.qualityForm.validate(valid => {
        if (valid) {
          // 组装数据
          const submitData = {
            qcId: this.formData.qcId,
            lineId: this.formData.lineId,
            shift: this.formData.shift,
            mpn: this.formData.mpn,
            lot: this.formData.lot,
            machineNumber: this.formData.machineNumber,
            qcfF: this.formData.qcfF,
            qcfM: this.formData.qcfM,
            qcfE: this.formData.qcfE,
            qceF: this.formData.qceF,
            qceM: this.formData.qceM,
            qceE: this.formData.qceE,
            moldCheck: this.formData.moldCheck,
            remark: this.formData.remark,
          }
          // 根据是新增还是编辑调用不同API
          const apiCall = this.currentId == 2
            ? updateQualityConfirmation(submitData)
            : addQualityConfirmation(submitData);


          apiCall.then(() => {
            this.$message.success(this.currentId == 2 ? '修改成功' : '新增成功')
            this.dialogVisible = false
            this.fetchData()
          }).catch(error => {
            this.$message.error(`操作失败: ${error.message}`)
          })
        }
      })
    },

    resetForm() {
      this.$refs.qualityForm.resetFields()
      this.formData = {
        lineId: '',
        shift: '',
        mpn: '',
        lot: '',
        qcfF: '',
        qcfM: '',
        qcfE: '',
        qceF: '',
        qceM: '',
        qceE: '',
        remark: '',
      }
    },





    getValueClass(row, machine, param) {
      const value = this.getMachineParam(row, machine, param)
      if (value === null) return 'empty-value'

      if (param === '贴合时间') {
        const numValue = parseFloat(value)
        if (numValue > 100) return 'warning-value'
        if (numValue > 120) return 'critical-value'
      }

      if (param === '吸嘴下压量') {
        const numValue = parseFloat(value)
        if (numValue > 12) return 'warning-value'
        if (numValue > 15) return 'critical-value'
      }

      return 'normal-value'
    },

    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())}`
    },

    formatTime(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`
    },

    padZero(num) {
      return num < 10 ? `0${num}` : num
    },

    handleFilter() {
      this.pagination.pageNum = 1
      this.fetchData()
    },

    resetFilter() {
      this.filterForm = {
        lineId: '',
        dateRange: [],
        mpn: '',
        lot: ''
      }
      this.handleFilter()
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.fetchData()
    },

    handleSortChange({ prop, order }) {
      console.log('排序:', prop, order)
    }
  }
}
</script>

<style scoped>
.quality-table-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.machine-header {
  background: #e3f2fd;
  font-weight: bold;
  text-align: center;
}

.machine-cell {
  text-align: center;
  font-weight: 500;
}

.normal-value {
  color: #4caf50;
}

.warning-value {
  color: #ff9800;
  font-weight: bold;
}

.critical-value {
  color: #f44336;
  font-weight: bold;
}

.empty-value {
  color: #9e9e9e;
  font-style: italic;
}

.status-tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-ok {
  background: #e8f5e9;
  color: #4caf50;
}

.machine-card {
  margin-bottom: 15px;
}

.machine-card:last-child {
  margin-bottom: 0;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

@media (max-width: 768px) {
  .filter-form {
    flex-direction: column;
  }

  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }

  .filter-form .el-select,
  .filter-form .el-input,
  .filter-form .el-date-editor {
    width: 100%;
  }
}
</style>